package com.hotel.core.alipay;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;

/**
 * @Date: 2023/10/25 10:13
 */
public class AliPayUtil {
    /**
     * 支付宝 申请我们的应用id*/
    private static final String APP_ID="2017091608770636";
    /**
     * 支付宝 上 我们应用的私钥*/
    private static final String PRIVATE_KEY="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCh1qI8uo1qhrcePsa5JUAoYUX8HfPuBt7kc90aCP1M/v61/uzaU/lyGQeChKV3jdDTn2Lcq6kT5JBl3TLiaYHmO6cId1nQAIUxiT9zhB9crc4wAx8CVabMbcqUefs7Xsp+YhhUgU5X6GOS3emkUeL7RegBnL8vayfEBeUDgBxsk/K/VygBA8sapsEhnoOrB6bhMY4GaJrxb0kg9Ej8x4kpExLcxkT+UgcOiJvh6vpBZo5CJsiPQkFvSsNsWY2uSDudSL/KqpMxz+yPfVvZDt4fOfyi+CfYR43Jlo4tsT7joqH2JT06BH+KdJyc1D3Lqw7w/WdmZtmoLghH0kRZawrLAgMBAAECggEAYYtpm+rhQ7zQ8HTr+DogknYW5Z/0H5qai93d/Uw/yEHFqlJt1iZZKlE1upBS311l6beesdzxeuD/u7X4bokjV27K/YpaYsl9fl74FJslAApuRXgMH68aawsd2CIxsBYxPL3JZl3Np6SVJ7eDlJwakFMRRK+CeIVAoaDf6R01hKctkYnnE0wT+ffQNKWsISoEyiKVT3g5fur7iPOuDlDXsfi6Mm+e75wCXTmRRHmb8lPBAMLV+Kj5DFxg8dwNz81Fs4ZM2Aq0lBaTfy1H1zSlM1m42wcsMYDcgdEH9aq+OgqK+cny6umgs7/Alg7IgV/9b7AhKdvAqLy2ERUJtooj2QKBgQDeIoDW3HuTq7sBaBnu63f7icT2RM3fApfOiGM4UDtxPvc5dS5S//o3E8p+rbp21FfBeyLOJFd9dg/eu+ETA+63QMPw4Kq4AH/EA5AFohaOQ0IKFDjYyxfyD8ajA4USDwdiaW2/vmMeAtGSv+W5zWb9/t49LOTwzEW904+yOGcmhQKBgQC6guDZ0Ob4o9nx5XwZXEe2di4MupARHceGzmolyDvs3Qi/w+8QntrDvfqIJoqoxOG5NVi3jtjkqtJtMaPyxqNWTabWOOTLbrsqlvPUmeCl0j3FVFKAGcV7/b9XkLvh1DtnIe6rhhZCVB4e4bL/katpOTgulhmSMaWIaztGU0F1DwKBgQCTeobdn/6vuSlsMqhdFppPN1W8R0wDjt4o8iYlwibk9e//hswdsPN307zyQ/dzY2FsBIvEHx6zHkpFD6nMDSVVJzuv1gmiJjqtccwR4V5mT0MuG+TuElCwlkbD/ddAeRfm/6Ys0oNN7oMjkiI8LKH/alI0fXT2Zji7YhWaNpZNXQKBgEU6q0duWS1VdGJrcgLf0+aQO0uSPEN+MD+Dgrb/ee7TpJm5mpUqwb0CWWoMFE/MtJRQjtujdDJ8jZrmYBqPTLWOIS1G9PXl5idK3Lq/Wzlxrmf+gpj19+2sJEfWe0a5xkrjt3mHTd/U5VFFKXHfmiZ2jLoOEPPI5c6bLudNo/BVAoGBAMvwRxLO4xb11Ip4rnEHkw3Qn8lrddoC3/m7haHYZ5DyGe8wdCdEi6wyk5MvlNQdqdVg5bqV0AiotIBcd5Pemabun2WaB11h/6SSb6wKY4Fnz+H155zaEww4no9BTG9llqQV7H8AS77dN1bxhcpE/MGFoB9JFU0D+BwXAnth4z1u";
    /**
     * 支付宝 申请应用的时候自动分配的公钥*/
    private static final String ALIPAY_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx7jJT+PSEM6ZiimTW0SGUfg4cJU04H/mQqkL2mk7KaHXFQqMh4US6xYkDlaEXzOOfxevuBqWOaB4/8TleO1CHZHXWHu9Xc+iYtJPNJGrxoGLM+6Cg9IafJTygRoaqdH0SoVMpxFdOpUftNdXHO+G0ZpS/7c1zpn8G64zN5J17IFrLcUlsEnSgOrJxsS2Q50b44er0KQlj76pehB2sTveHS2vdhqXzrv+oq99XtUKEY1a3nwDjXneI7YYKLHD9KU53pti/ibLDkOEjO4+DRowd+wfSwkmWGVL3X320mvCfrg/aMN71B/cyyhW0mQ4cxqh2UcnpxLm0v/+uC7dSCyAJwIDAQAB";
    /**
     * 支付成功的异步通知地址*/
    //private static final String NOTIFY_URL="https://y192580h27.goho.co/pay/alipay/cb";
    private static final String NOTIFY_URL="http://localhost:9094/pay/alipay/cb";
    /**
     * 支付成功的显示的页面*/
    private static final String RETURNUrl="http://localhost:9094/pay/alipay/cb";

    private static AlipayClient client;
    static {
        //构造client
        client = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                APP_ID,PRIVATE_KEY,"JSON",
                "UTF-8",ALIPAY_PUBLIC_KEY,"RSA2");
    }

    /**
     * 1.生成支付信息
     * 统一收单下单并支付页面接口
     *
     * 调用此接口返回一个 支付宝的界面 ，用于支付宝 用户登录进行支付 // 扫码支付
     * @param no 订单号
     * @param title 订单标题
     * @param money 订单金额
     * @return 支付页面信息
     * */
    public static String createPay(String no,double money,String title) {
        //1.创建请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //2.设置请求参数 只关心必传内容
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(NOTIFY_URL);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(RETURNUrl);
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", no);
        //支付金额，最小值0.01元 防止金额弄错
        bizContent.put("total_amount", 0.01); // 只能冲 0.01分
        //订单标题，不可使用特殊符号
        bizContent.put("subject", title);
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toJSONString());

        //3.获取响应
        try {
            AlipayTradePagePayResponse response = client.pageExecute(request);
            if (response.isSuccess()) {
                return response.getBody(); // 响应的html
            }
        } catch (AlipayApiException e) {}
        return null;
    }
    /**
     * 2.统一收单交易退款接口
     * @param no 订单号
     * @param rno 本次退款订单号
     * @param money 退款金额
     * */
    public static boolean refundPay(String no,String rno,double money){
        //1.实例化 请求对象
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        //2.设置请求信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", no);
        bizContent.put("refund_amount", money);
        bizContent.put("out_request_no", rno);
        request.setBizContent(bizContent.toString());
        //3.发起请求 获取响应
        try {
            AlipayTradeRefundResponse response = client.execute(request);
            if(response.isSuccess()){
                return response.getFundChange().equals("Y");
            }
        } catch (AlipayApiException e) {}
        return false;
    }
    /**
     * 3.统一收单交易查询
     * @param no 订单号
     * @return 交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）*/
    public static String queryPay(String no){
        //1.实例化 请求对象
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        //2.设置请求参数
        request.setBizContent("{\"out_trade_no\":\""+no+"\"}");
        //3.执行请求 获取响应
        try {
            AlipayTradeQueryResponse response = client.execute(request);
            if(response.isSuccess()){
                return response.getTradeStatus();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 4.统一收单交易退款查询
     * @param no 订单号
     * @param qno 退款订单号
     * @return 退款处理成功: REFUND_SUCCESS*/
    public static String queryRefound(String no,String qno){
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", no);
        bizContent.put("out_request_no", qno);


        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeFastpayRefundQueryResponse response = client.execute(request);
            if(response.isSuccess()){
                return response.getRefundStatus();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 6.统一收单交易关闭接口
     * @param no 订单号*/
    public static boolean closePay(String no){
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", no);
        request.setBizContent(bizContent.toString());
        try {
            AlipayTradeCloseResponse response = client.execute(request);
            return response.isSuccess();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 7.对账单
     * 日账单格式为yyyy-MM-dd
     * 月账单格式为yyyy-MM*/
    public static String queryUrl(String date){
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizContent("{" +
                "  \"bill_type\":\"trade\"," +
                "  \"bill_date\":\""+date+"\"}");
        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse response = client.execute(request);
            if(response.isSuccess()){
                return response.getBillDownloadUrl();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

}
